import React, {
  Component,
  createRef,
  createContext,
  useRef,
  useState,
  useEffect,
} from "react";
import PropType from "prop-types";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import gsap from "gsap"; //动画库
import Stats from "stats.js"; //性能监控
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader.js"; // FBX 模型加载器
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"; //模型加载器
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader"; //模型解压缩

import "./Home.css";
import TagHook from "./components/tagHook";

import { loadShaderFromFile } from "./utlis";

import { CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer.js"; //// 引入CSS2模型对象CSS2DObject
import { CSS2DRenderer } from "three/examples/jsm/renderers/CSS2DRenderer.js"; // 引入CSS2渲染器CSS2DRenderer

import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer"; //EffectComposer 效果组合器 它是处理 WebGLRenderer 效果的 接收 renderer为参数
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass"; // RenderPass 处理通道 它是处理 scene 场景和相机 camera 的。 接收 scene camera 为参数
import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass"; //UnrealBloomPass 泛光通道
import { FXAAShader } from "three/examples/jsm/shaders/FXAAShader.js"; //添加抗锯齿的效果
import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass"; // 高亮发光描边通道 OutlinePass(画布宽高二维向量，场景scene,相机camera)

import { SMAAPass } from "three/examples/jsm/postprocessing/SMAAPass.js"; // SMAA抗锯齿通道

import { ShaderPass } from "three/examples/jsm/postprocessing/ShaderPass";
import { GammaCorrectionShader } from "three/examples/jsm/shaders/GammaCorrectionShader.js"; // 伽马校正后处理Shader

import WebGL from "three/examples/jsm//capabilities/WebGL.js";
import { ImprovedNoise } from "three/examples/jsm/math/ImprovedNoise"; //柏林噪声
// @ts-ignore
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min";
import { Side } from "three";
import HeatMap from "heatmap-ts";




if (WebGL.isWebGL2Available() === false) {
  document.body.appendChild(WebGL.getWebGL2ErrorMessage());
}

const width = window.innerWidth; //屏幕宽度
const height = window.innerHeight; //屏幕高度

// 渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true, //开启优化锯齿
});
renderer.setPixelRatio(window.devicePixelRatio); // 设置设备像素比。通常用于避免HiDPI设备上绘图模糊
renderer.setSize(width, height); // 将输出canvas的大小调整为(width, height)并考虑设备像素比，
// renderer.outputEncoding = THREE.sRGBEncoding; //定义渲染器的输出编码
// 相机
const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  0.1,
  1200
);
camera.position.set(50, 50, 90);
// 场景
const scene = new THREE.Scene();
scene.background= new THREE.Color('#fff');

// 轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
// controls.target.set(0, 12, 0);

// 性能监测 (这个不是three必须项)
const stats = new Stats(); // 性能监测
const loader = new GLTFLoader(); //gltf模型加载器
 
const dracoLoader = new DRACOLoader(); //模型解压缩
let rawshaderMaterial: any;
console.log("1111111111111111111", document.getElementById("view"));

const ReactDemo = () => {
  useEffect(() => {
    init();
  }, []);

  const init = () => {
    
   const heatMap =  handle_heatMap()
    // 定义高斯函数

    const container = document.createElement("div");
    document.body.appendChild(container);

    const axesHelper = new THREE.AxesHelper(90); // 辅助线
    scene.add(axesHelper);

    const textuerLoader = new THREE.TextureLoader();
    const texture11 = textuerLoader.load("./太阳.jpg");

    // 纹理加载
    const texture = new THREE.Texture(heatMap.renderer.canvas);
    // 这些常量定义了纹理贴图的 wrapS 和 wrapT 属性，定义了水平和垂直方向上纹理的包裹方式
    texture.wrapS = THREE.MirroredRepeatWrapping;
    texture.wrapT = THREE.MirroredRepeatWrapping;
    texture.mapping =THREE.CubeUVReflectionMapping;
    texture.repeat.set(1, 1 );
    texture.needsUpdate=true;





  


    const MeshBasicMaterial =  new THREE.MeshBasicMaterial( {
      map:texture
      } )
    //平面
    const floor = new THREE.Mesh(
      new THREE.PlaneGeometry(1, 1, 64, 64),
      MeshBasicMaterial
      // rawshaderMaterial
    );
    scene.add(floor);




    const light = new THREE.AmbientLight( 0x404040 ); // soft white light
    scene.add( light );

    
    const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
    hemiLight.position.set( 0, 1, 0 );
    scene.add( hemiLight );

    const dirLight = new THREE.DirectionalLight( 0xffffff );
    dirLight.position.set( 0, 1, 0 );
    scene.add( dirLight );
      // 模型


      dracoLoader.setDecoderPath('./draco');
      loader.setDRACOLoader(dracoLoader);
      loader.load( '3D/B工厂.glb' , function ( object ) {

        // 获取模型的尺寸大小
        const box3 = new THREE.Box3() //表示三维空间中的一个轴对齐包围盒
        box3.expandByObject(object.scene) //包裹在包围盒中的3d对象 Object3D。
        const v3 = new THREE.Vector3()
        box3.getSize(v3) //target — 如果指定了target ，结果将会被拷贝到target。返回包围盒的宽度，高度，和深度。
	      console.log('size--------->', v3)

        const geometry = new THREE.PlaneGeometry( v3.x, v3.z );
        const material = new THREE.MeshBasicMaterial( { map:texture, side: THREE.DoubleSide} );
        const plane = new THREE.Mesh( geometry, material );
        plane.rotation.x = Math.PI / 2;
        plane.position.y =1;
        scene.add( plane );
  
        scene.add( object.scene ); 
  
      } );




      const geometry = new THREE.SphereGeometry( 2, 32, 16 );
      const sphere = new THREE.Mesh( geometry, MeshBasicMaterial );
      sphere.position.y =20
      scene.add( sphere )










    // 性能监测
    container.appendChild(stats.dom);

    container.appendChild(renderer.domElement);

    window.addEventListener("resize", onWindowResize);
    renderer.domElement.addEventListener("click", handleModelClick);
  };

  function onWindowResize() {
    camera.aspect = width / height;
    camera.updateProjectionMatrix();

    renderer.setSize(width, height);
  }

  function handleModelClick(event: MouseEvent) {
    const raycaster = new THREE.Raycaster();
    const pointer = new THREE.Vector2();
    pointer.x = (event.clientX / width) * 2 - 1;
    pointer.y = -(event.clientY / height) * 2 + 1;
    // 通过摄像机和鼠标位置更新射线
    raycaster.setFromCamera(pointer, camera);

    // 计算物体和射线的焦点
    const intersects: any = raycaster.intersectObjects(scene.children);

    console.log(intersects);
  }

  function handle_heatMap(){
    const heatMap = new HeatMap({
      container: document.getElementById("view") as HTMLElement,
      // container: document.body,
      maxOpacity: 0.6,
      radius: 50,
      blur: 0.9,
    });
    let pointValue=[]
    let len =500;
    let max = 0
    while (len--) {
      var val = Math.floor(Math.random()*100);
      max = Math.max(max, val);
      var point = {
         x: Math.floor(Math.random()*width), //数据点的x坐标，一个数字
         y: Math.floor(Math.random()*height), //数据点的y坐标，一个数字
         value: val //数据点（x，y）处的值
     };
     pointValue.push(point);
  }
    heatMap.setData({
      max: 0,
      min: 0,
      data:pointValue,
    });

    return heatMap
  }

  //
  const timeClock = new THREE.Clock(); // 获取时间
  function animate() {
    requestAnimationFrame(animate);

    const time = timeClock.getElapsedTime();
    // if (rawshaderMaterial) {
    //   rawshaderMaterial.uniforms.uTime.value = time;
    // }

    renderer.render(scene, camera);
    controls.update();

    stats.update();
  }

  animate();

  return <div id="view" style={{opacity:1}}></div>;
};

export default ReactDemo;
